package com.example.myapplication.fragment

import android.util.Log
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.Observer
import androidx.navigation.NavOptions
import androidx.navigation.fragment.findNavController
import com.example.myapplication.MainViewModel
import com.example.myapplication.R
import com.example.myapplication.databinding.FragmentLoginBinding

class LoginFragment : BaseFragment<FragmentLoginBinding>(){
    private val mViewModel: MainViewModel by activityViewModels()

    override fun initBinding(): FragmentLoginBinding {
        return FragmentLoginBinding.inflate((layoutInflater))
    }

    override fun initView() {
       // mViewModel.deleteAll()
        mViewModel.userList.observe(viewLifecycleOwner, Observer { users ->
            if (users != null) {
                Log.d("LoginFragment", "Observed users data: $users")
            } else {
                Log.e("LoginFragment", "User list is null")
            }
        })

        mBinding.register.setOnClickListener {
            findNavController().navigate(R.id.action_loginFragment_to_registerFragment)
        }

        mBinding.ToLoginIn.setOnClickListener {
            val account = mBinding.Account.text.toString()
            val password = mBinding.editTextTextPassword.text.toString()

            when {
                account.isEmpty() -> {
                    showAlert("提示", "请输入账号")
                }
                password.isEmpty() -> {
                    showAlert("提示", "请输入密码")
                }
                else -> {
                    val userList = mViewModel.userList.value
                    if (userList == null) {
                        Log.e("LoginFragment", "User list is null")
                        showAlert("错误", "用户列表为空，请稍后重试")
                        return@setOnClickListener
                    }
                    if (userList.isEmpty()) {
                        Log.e("LoginFragment", "User list is empty")
                        showAlert("错误", "用户列表为空，请稍后重试")
                        return@setOnClickListener
                    }
                    for (user in userList) {
                        Log.d("LoginFragment", "User: ${user.id}, ${user.account}, ${user.password}")
                    }
                    mViewModel.login(account, password)

                }
            }
        }
        mViewModel.loggedInUser.observe(viewLifecycleOwner, Observer { loggedInUser ->
            if (loggedInUser != "") {
                Toast.makeText(requireContext(), "登入成功", Toast.LENGTH_SHORT).show()
                mViewModel.Logged_user.value = loggedInUser
                val navOptions = NavOptions.Builder()
                    .setPopUpTo(R.id.loginFragment, true)  // 清除之前的所有Fragment
                    .build()
                if(mViewModel.findUserByAccount(loggedInUser)?.selfIntroduction==""){
                    findNavController().navigate(R.id.action_loginFragment_to_userFirstLoginFragment,null,navOptions)
                }else{
                    findNavController().navigate(R.id.action_loginFragment_to_homeFragment,null,navOptions)
                }
            } else {
                showAlert("提示", "请输入正确的账号和密码")
            }
        })




    }

    private fun showAlert(title: String, message: String) {
        AlertDialog.Builder(requireContext())
            .setTitle(title)
            .setMessage(message)
            .setPositiveButton("确定") { dialog, _ ->
                dialog.dismiss()
            }
            .show()
    }


}